package com.gzhryc.shared_device.common.device.services;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.base.IDeviceEventListener;
import com.gzhryc.shared_device.common.device.dao.DeviceTypeDao;
import com.gzhryc.shared_device.common.device.dao.db.DeviceType;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.common.device.services.dto.DeviceTypeSearch;

public class DeviceTypeService {

    static Logger log = Logger.getLogger(DeviceTypeService.class);

    public static DeviceTypeService self() {
        return MultiDBTools.getService(DeviceTypeService.class, true);
    }

    public static DeviceTypeService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, DeviceTypeService.class, true);
    }

    DeviceTypeDao dao;

    public DeviceTypeService(String jdbcKey) {
        dao = new DeviceTypeDao(jdbcKey);
    }

    public List<DeviceType> findAll(){
        try {
            return dao.findAll();
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<DeviceType> findBySearch(DeviceTypeSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().notIn("id",search.getNotInIds());
        conditions.desc("createDate");

        try {
            return dao.findByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countBySearch(DeviceTypeSearch search){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().notIn("id",search.getNotInIds());
        try {
            return dao.count(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public List<DeviceType> findByIds(List<String> ids){
        if(ids != null && ids.size() > 0) {
            Conditions conditions = new Conditions(DeviceService.class);
            conditions.and().in("id", ids);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public DeviceType getById(String id){
        try {
            return dao.getById(id);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public boolean add(DeviceType deviceType) throws LogicException {
        deviceType.setCreateDate(new Date());
        try {
           return dao.insert(deviceType) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean updateNotNull(DeviceType deviceType, IDeviceEventListener deviceEventListener) throws LogicException{
        DeviceType temp = getById(deviceType.getId());
        if(temp == null){
            throw new LogicException("未找到设备类型");
        }
        boolean updateName = false;
        if(StringTools.isNotBlank(deviceType.getName()) && !temp.getName().equals(deviceType.getName())){
            updateName = true;
        }

        JdbcSession.begin();
        try {
            if(dao.updateNotNull(deviceType) > 0){
                if(updateName){
                    if(DeviceService.self().updateDeviceTypeName(deviceType.getId(),deviceType.getName())){
                        if(deviceEventListener.updateDeviceTypeName(deviceType.getId(),deviceType.getName())){
                            JdbcSession.commit();
                            return true;
                        }
                    }
                }else {
                    JdbcSession.commit();
                    return true;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        } finally {
            JdbcSession.end();
        }
        return false;
    }

    public boolean increaseProduceBatchIndex(String id,Integer produceBatchIndex,Integer newProduceBatchIndex){
        Conditions conditions = new Conditions(DeviceType.class);
        conditions.and().is("id",id);
        conditions.and().is("produceBatchIndex",produceBatchIndex);

        DeviceType updateEntity = new DeviceType();
        updateEntity.setProduceBatchIndex(newProduceBatchIndex);

        try {
            return dao.updateNotNull(updateEntity,conditions) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean deleteById(String id) throws LogicException{
        if(StringTools.isNotBlank(id)) {
            //检查是否有设备
            DeviceSearch search = new DeviceSearch();
            search.setDeviceTypeId(id);
            Long total = DeviceService.self().countBySearch(search);
            if(total > 0){
                throw new LogicException("该类型存在设备，请先删除");
            }

            JdbcSession.begin();
            try {
                if(dao.deleteById(id) > 0){
                    if(DeviceTypeFuncService.self().deleteByTypeId(id)){
                        JdbcSession.commit();
                        return true;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            } finally {
                JdbcSession.end();
            }
        }
        return false;
    }
}
